package org.kl.bf.utils;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;

/**
 * 动态创建footer
 * @author QJ
 * @date 2014年9月11日
 */
public class KLFooterFilter {
	
	public enum Operator {
		SUM,CNT,AVG,MAX,MIN
	}

	public String fieldName;
	public String value;
	public Operator operator;

	public KLFooterFilter(String fieldName, Operator operator, String value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME或者OPERATOR-JavaType_FIELDNAME
	 */
	public static Map<String, KLFooterFilter> parse(Map<String, Object> footerParams) {
		Map<String, KLFooterFilter> filters = Maps.newTreeMap();
		for (Entry<String, Object> entry : footerParams.entrySet()) {
			String key = entry.getKey();
			String value = (String)entry.getValue();
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid footer filter name");
			}
			String filedName = names[1];
			String[] opers = StringUtils.split(names[0], "-");
			String operatorStr = names[0];

			if (opers.length == 2) {
				operatorStr = opers[0];
			}

			Operator operator = Operator.valueOf(operatorStr);
			if (StringUtils.isBlank((String) value)) {
				continue;
			}
			// 创建footerFilter
			KLFooterFilter filter = new KLFooterFilter(filedName, operator, value);
			filters.put(key, filter);
		}
		return filters;
	}
}
